﻿using System;
using System.Reflection;

namespace EasyLib.Utils
{
    public class DataConvertUtils
    {
        /// <summary>
        /// 获取引用类型的值。
        /// </summary>
        /// <typeparam name="TClass">要获取的值的数据类型，必须是引用类型。</typeparam>
        /// <param name="value">要转换的值。</param>
        /// <returns>返回转换后的数据。</returns>
        public static TClass GetClassValue<TClass>(object value)
            where TClass : class
        {
            return value is DBNull || value == null ? default(TClass) : value as TClass;
        }

        /// <summary>
        /// 获取值类型的值。
        /// </summary>
        /// <param name="value">要转换的值</param>
        /// <returns>返回转换后的数据。</returns>
        /// <typeparam name="TStruct">要获取的值的数据类型，必须是值类型。如,int、bool</typeparam>
        public static TStruct GetStructValue<TStruct>(object value)
            where TStruct : struct
        {
            if (value is DBNull || value == null)
            {
                return default(TStruct);
            }

            if (typeof(TStruct).IsEnum)
            {
                return (TStruct)Enum.Parse(typeof(TStruct), value.ToString());
            }
            MethodInfo method = typeof(TStruct).GetMethod("Parse",
                                                          BindingFlags.Static | BindingFlags.Public,
                                                          null,
                                                          new[] { typeof(string) }, null);

            if (method != null)
                return (TStruct)(method.Invoke(null, new object[] { value.ToString() }));

            return (TStruct)value;
        }
    }
}